import React from "react";
import {Button} from "antd";
import {IconFont} from "@/components/Icon";
import {RootState, useDispatch, useSelector} from "@/store";
import {setGlobalState} from "@/store/modules/global";
import styles from '@/views/login/index.module.less'

const SwitchDark: React.FC = () => {
    const dispatch = useDispatch();
    const {isDark} = useSelector((state: RootState) => state.globalSlice);
    const themeChange = (event) => {
        const isAppearanceTransition = document.startViewTransition && !window.matchMedia('(prefers-reduced-motion: reduce)').matches
        if (!isAppearanceTransition || !event) {
            dispatch(setGlobalState({key: "isDark", value: !isDark}))
            return
        }
        const x = event.clientX
        const y = event.clientY
        const endRadius = Math.hypot(
            Math.max(x, innerWidth - x),
            Math.max(y, innerHeight - y)
        )
        const transition = document.startViewTransition(() => {
        })
        transition.ready.then(() => {
            const clipPath = [
                `circle(0px at ${x}px ${y}px)`,
                `circle(${endRadius}px at ${x}px ${y}px)`,
            ]
            document.documentElement.animate(
                {
                    clipPath: !isDark ? [...clipPath].reverse() : clipPath,
                },
                {
                    duration: 400,
                    easing: 'ease-in',
                    pseudoElement: !isDark
                        ? '::view-transition-old(root)'
                        : '::view-transition-new(root)',
                }
            )
            dispatch(setGlobalState({key: "isDark", value: !isDark}))
        })
    }
    return (
        <Button
            type="text"
            size="large"
            className={styles.switch_dark}
            icon={<IconFont style={{fontSize: 22}} type={isDark ? "icon-sun" : "icon-moon"}/>}
            onClick={themeChange}
        ></Button>
    );
};

export default SwitchDark;
